package com.herui.iot.data;


import com.herui.sdyu_lib.http.callback.Callback;
import com.herui.sdyu_lib.utils.LogUtils;
import com.herui.sport_care.request.SportResponse;

/**
 * Created by amanda.shan on 2021/10/19.
 */
public abstract class BaseCallBack<T> extends Callback.CommonCallback<String> {

    private Callback.CommonCallback<T> callback;

    public BaseCallBack(Callback.CommonCallback<T> callback) {
        this.callback = callback;
    }

    @Override
    public void onSuccess(String s) {

        LogUtils.d(s);
        SportResponse<T> apiResponse;
        try {
            apiResponse = getApiResponse(s);
            if (apiResponse.getSuccess()) {
                callback.onSuccess(apiResponse.getResult());
                onResult(apiResponse.getResult());
            } else {
                switch (apiResponse.getCode()){
                    case "400":
                        callback.onError(null, apiResponse.getCode()+":%s", "参数错误");
                        break;
                    case "404":
                        callback.onError(null, apiResponse.getCode()+":%s", "请求不存在");
                        break;
                    case "500":
                        callback.onError(null, apiResponse.getCode()+":%s", "服务器异常");
                        break;
                    default:
                        callback.onError(null, apiResponse.getCode()+":%s", apiResponse.getMessage());
                }
            }
        } catch (Exception e) {
            callback.onError(e, "", "");
            e.printStackTrace();
        }
    }

    public abstract SportResponse<T> getApiResponse(String s) throws Exception;

    public void onResult(T t){

    }

    @Override
    public void onError(Throwable throwable, String s, String s1) {
        if (s == null) {
            s = throwable.getMessage();
        }
        switch ( s){
            case "400":
                callback.onError(null, s+":%s", "参数错误");
                break;
            case "404":
                callback.onError(null, s+":%s", "请求不存在");
                break;
            case "500":
                callback.onError(null, s+":%s", "服务器异常");
                break;
            default:
                callback.onError(throwable, s + ":%s", s1);
        }
    }
}
